package com.llp.declaresystem.controller;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.llp.declaresystem.domain.Result;
import com.llp.declaresystem.domain.dto.HighQueryProjectDto;
import com.llp.declaresystem.domain.dto.ProjectDto;
import com.llp.declaresystem.domain.dto.UserDto;
import com.llp.declaresystem.domain.entity.Project;
import com.llp.declaresystem.domain.entity.ProjectCategory;
import com.llp.declaresystem.domain.entity.Unit;
import com.llp.declaresystem.domain.entity.User;
import com.llp.declaresystem.mapper.ProjectMapper;
import com.llp.declaresystem.mapper.UserMapper;
import com.llp.declaresystem.service.ProjectCategoryService;
import com.llp.declaresystem.service.UnitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @BelongsProject: declare-system
 * @BelongsPackage: com.llp.declaresystem.controller
 * @Author: bovan
 * @Date: 2022/11/26 16:40
 * @Description:
 */
@RestController
@RequestMapping("/api/unit")
public class UnitManagerController {
    @Autowired
    private UnitService unitService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ProjectCategoryService projectCategoryService;
    @Autowired
    private ProjectMapper projectMapper;

    /**
     * 根据uid查询单位信息
     *
     * @param uid
     * @return
     */
    @GetMapping("/unitInfo/{uid}")
    public Result selectUnitInfoByUid(@PathVariable("uid") Integer uid) {
        Unit unit = unitService.selectUnitInfoByUid(uid);
        if (unit != null) {
            return new Result<>(200, "操作成功", unit);
        } else {
            return new Result<>(400, "操作失败", null);
        }
    }

    /**
     * 根据uid查询项目分类信息
     *
     * @param uid
     * @return
     */
    @GetMapping("/select/categories/{uid}")
    public Result selectAllCategories(@PathVariable("uid") Integer uid) {
        List<ProjectCategory> projectCategory = unitService.selectAllProjectCategory(uid);
        if (projectCategory != null) {
            return new Result<>(200, "操作成功",
                    MapUtil.builder().put("categories", projectCategory).map());
        } else {
            return new Result<>(400, "操作失败", null);
        }
    }

    /**
     * 根据categoryid查询项目分类信息
     *
     * @param cid
     * @return
     */
    @GetMapping("/select/category/{cid}")
    public Result selectCategorie(@PathVariable("cid") Integer cid) {
        ProjectCategory projectCategory = unitService.selectProjectCategory(cid);
        if (projectCategory != null) {
            return new Result<>(200, "操作成功",
                    MapUtil.builder().put("categories", projectCategory).map());
        } else {
            return new Result<>(400, "操作失败", null);
        }
    }

    /**
     * 根据uid更新单位信息
     *
     * @param unit
     * @return
     */
    @PostMapping("/updateUnitInfo")
    public Result updateUnitInfo(@RequestBody Unit unit) {
        int res = unitService.updateByUid(unit);
        if (res != 0) {
            return new Result<>(200, "操作成功", null);
        } else {
            return new Result<>(400, "操作失败", null);
        }
    }

    /**
     * 根据uid修改密码
     *
     * @param userDto
     * @return
     */
    @PostMapping("/updatePwd")
    public Result updatePwdByUid(@Validated @RequestBody UserDto userDto) {
        User user = userMapper.selectByUid(userDto.getUid());
        if (user != null) {
            if (user.getPassword().equals(userDto.getOldPassword())) {
                int res = unitService.updatePwdByUid(userDto);
                if (res == 1) {
                    return new Result<>(200, "修改成功", null);
                }
            } else {
                return new Result<>(400, "旧密码输入错误", null);
            }
        }
        return new Result<>(400, "修改失败", null);
    }

    /**
     * 根据projectId查询项目信息
     *
     * @param pid
     * @return
     */
    @GetMapping("/select/project/{pid}")
    public Result selectProjectByPid(@PathVariable("pid") Integer pid) {
        Project project = unitService.selectProjectByPid(pid);
        return new Result<>(200, "操作成功",
                MapUtil.builder()
                        .put("projectInfo", project)
                        .map());
    }

    /**
     * 提交项目信息
     *
     * @param project
     * @return
     */
    @PostMapping(value = "/submitProjectInfo")
    public Result submitProjectInfo(@RequestBody Project project) {
        int res = unitService.updateProjectInfo(project);
        if (res != -1) {
            return new Result<>(200, "提交成功", null);
        } else {
            return new Result<>(400, "提交失败", null);
        }
    }

    /**
     * 申请项目
     *
     * @param project
     * @return
     */
    @PostMapping(value = "/applyProject")
    public Result applyProject(@RequestBody Project project) {
        int res = unitService.insertProject(project);
        if (res != 1) {
            return new Result<>(400, "申请失败", null);
        }
        return new Result<>(200, "申请成功", null);
    }

    /**
     * 简单查询
     *
     * @param projectContent
     * @return
     */
    @GetMapping(value = "/selectProject/projectContent/pc={projectContent}")
    public Result selectProjectByProjectContent(@PathVariable("projectContent") String projectContent) {
        String content = '%' + projectContent + '%';
        Set<ProjectDto> projects = unitService.selectByProjectContent(content);
        if (projects.isEmpty()) {
            return new Result<>(400, "查询失败", null);
        }
        return new Result<>(200, "查询成功", MapUtil.builder().put("projectInfo", projects).map());
    }

    /**
     * 高级查询
     *
     * @param highQueryProjectDto
     * @return
     */
    @PostMapping(value = "/selectProject/highQuery")
    public Result highQueryProject(@RequestBody HighQueryProjectDto highQueryProjectDto) {
        Set<HighQueryProjectDto> highQueryProjectDtos = unitService.highQueryProject(highQueryProjectDto);
        {
            if (highQueryProjectDtos.isEmpty()) {
                return new Result<>(400, "查询失败", null);
            }
            return new Result<>(200, "查询成功", MapUtil.builder().put("projectInfo", highQueryProjectDtos).map());
        }
    }

    @PostMapping("pageCondition/{current}/{limit}")
    public Result pageCondition(@PathVariable long current, @PathVariable long limit, @RequestBody(required = false) HighQueryProjectDto highQueryProjectDto) {
        //创建page对象
        Page<ProjectCategory> pageProject = new Page<>(current, limit);
        //构建条件
        QueryWrapper<ProjectCategory> wrapper = new QueryWrapper<>();
        //多条件组合查询
        String categoryName = highQueryProjectDto.getCategoryname();
        System.out.println("categoryname:"+categoryName);
        Date repStartTime = highQueryProjectDto.getRepStartTime();
        Date repStopTime = highQueryProjectDto.getRepStopTime();
        String capital = highQueryProjectDto.getCapital();

        if (!StringUtils.isEmpty(categoryName)) {
            //构建条件
            wrapper.like("categoryname", categoryName);
        }
        if (!StringUtils.isEmpty(repStartTime)) {
            wrapper.ge("rep_start_time", repStartTime);
        }
        if (!StringUtils.isEmpty(repStopTime)) {
            wrapper.le("rep_stop_time", repStopTime);
        }

        //调用方法实现条件查询
        projectCategoryService.page(pageProject, wrapper);

//        long total = pageProject.getTotal();//总记录数
        List<ProjectCategory> records = pageProject.getRecords();   //数据list集合
        Set<HighQueryProjectDto> hqpjs = new HashSet<>();
//        if(!StringUtils.isEmpty(capital)){
        for (int i = 0; i < records.size(); i++) {
            List<HighQueryProjectDto> highQueryProjectDtos = projectMapper.selectByCategoryidAndCapital(records.get(i).getCategoryid(), capital);
            hqpjs.addAll(highQueryProjectDtos);
        }
        int total = hqpjs.size();
        return new Result<>(200, "查询成功",
                MapUtil.builder()
                        .put("total", total)
                        .put("rows", hqpjs)
                        .map());
/*        }else{
            return new Result<>(200,"查询成功",
                    MapUtil.builder().put("total", total)
                            .put("rows", records)
                            .map());
        }*/

    }

}
